const Coupon_user = require('../../models/Coupon_user')
const Coupon = require('../../models/Coupon')

//用户拥有哪些优惠券
exports.getUserCouponId = async function (userId) {

    const result = await Coupon_user.findAll({ //查询配置，查询条件
        where: {
            userId
        },
        attributes: ['couponId'],
        raw: true
    }).catch(()=>{})
    // console.log(result.map(item=>item.couponId));
    if (result != '') return {
        data: result.map(item => item.couponId),
        meta: {
            msg: '查询成功',
            status: '200'
        }
    }
    return {
        data: {},
        meta: {
            msg: '暂无数据或用户不存在',
            status: '404'
        }
    }
}

// 查询优惠券详情
exports.getUserCoupon = async function (couponId) {
    const result = await Coupon.findAll({ //查询配置，查询条件
        where: {
            id: couponId
        },
        raw: true
    }).catch(()=>{})
    // console.log(result);
    if (result != '') return {
        data: result,
        meta: {
            msg: '获取优惠券成功',
            status: '200'
        }
    }
    return {
        data: '',
        meta: {
            msg: '优惠券id不存在',
            status: '404'
        }
    }
}


exports.DeleteUserCoupon = async function (userId,couponId) {
    Coupon_user.destroy({
        where: {
            userId,
            couponId
        }
    }).catch(()=>{})
}

exports.addUserCoupon = async function (userId,couponId) {
    const result = await Coupon_user.findAll({ //查询配置，查询条件
        where: {
            userId,
            couponId
        }
    }).catch(()=>{})
    if(result != '') return '0'
    console.log(userId,couponId);
    Coupon_user.create({
        userId,
        couponId
    }).catch(()=>{})
    return '1'
}


